<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
  <title>日程管理系统 - 管理首页</title>
  <link href="/css/bootstrap.css" rel="stylesheet">
  <script src="/js/moment.min.js"></script>
  <script src="/js/jquery-3.5.1.min.js" crossorigin="anonymous"></script>
  <script src="/js/bootstrap.bundle.min.js" crossorigin="anonymous"></script>

  <style>
    /* 设置左右布局 */
    .container-fluid {
      display: flex;
    }

    .sidebar {
      width: 250px;
      height: 100vh;
      background-color: #f8f9fa;
      border-right: 1px solid #ddd;
    }

    .sidebar .nav-item {
      padding: 10px;
    }

    .main-content {
      flex-grow: 1;
      padding: 20px;
    }

    .navbar-nav .dropdown-menu {
      padding: 0.05rem 0;
      font-size: 0.875rem;
    }

    .dropdown-item {
      padding: 0.5rem 1rem;
    }
  </style>

</head>
<body>
<!-- 导航栏 -->
<nav class="navbar navbar-dark bg-dark">
  <div class="container-fluid">
    <a class="navbar-brand" href="#">日程管理系统</a>
    <ul class="navbar-nav ms-auto">
      <li class="nav-item dropdown">
        <a class="nav-link dropdown-toggle" href="#" id="userDropdown" role="button" data-toggle="dropdown" aria-expanded="false">
          <!-- 动态设置用户头像 -->
          <img id=’avatar‘ th:src="${user.avatar != null ? user.avatar : '/img/avatar.jpg'}" class="rounded-circle" alt="Avatar" style="width:30px;">
        </a>
        <ul class="dropdown-menu dropdown-menu-end" aria-labelledby="userDropdown">
          <li><a class="dropdown-item" th:href="@{/logout}">退出</a></li>
        </ul>
      </li>
    </ul>
  </div>
</nav>

<div class="container-fluid">
  <!-- 左侧菜单栏 -->
  <div class="sidebar">
    <ul class="nav flex-column">
      <li class="nav-item">
        <a class="nav-link active" href="#" id="scheduleMenu">
          <i class="fas fa-calendar-alt"></i> 日程信息管理
        </a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#" id="profileMenu">
          <i class="fas fa-user"></i> 个人信息
        </a>
      </li>
    </ul>
  </div>
  <!-- 右侧内容区域 -->
  <div class="main-content">
    <!-- 日程信息管理页面 -->
    <div id="scheduleContent">
      <h4>日程信息管理</h4>
      <div class="row">
        <div class="col-md-6">
          <input type="text" class="form-control" placeholder="按关键词搜索" id="content">
        </div>
        <div class="col-md-6">
          <button type="button" class="btn btn-primary" id="searchSchedule">查询</button>
          <button type="button" class="btn btn-success ms-2" data-toggle="modal" data-target="#addScheduleModal">新增日程信息</button>
        </div>
      </div>
      <hr>
      <table class="table table-striped">
        <thead>
        <tr>
          <th>日程ID</th>
          <th>用户名</th>
          <th>日程内容</th>
          <th>预约时间</th>
          <th>提醒时间</th>
          <th>操作</th>
        </tr>
        </thead>
        <tbody>
        <tr th:each="schedule : ${schedules}">
          <td th:text="${schedule.id}"></td>
          <td th:text="${schedule.username}"></td>
          <td th:text="${schedule.content}"></td>
          <td th:text="${#dates.format(schedule.scheduledate, 'yyyy-MM-dd HH:mm')}"></td>
          <td th:text="${#dates.format(schedule.remindtime, 'yyyy-MM-dd HH:mm')}"></td>
          <td>
            <button type="button" id="deleteSchedule" class="btn btn-danger btn-sm deleteSchedule" th:data-id="${schedule.id}">删除</button>
            <button type="button" id="updateSchedule" class="btn btn-warning btn-sm updateSchedule" th:data-id="${schedule.id}" data-toggle="modal" data-target="#addScheduleModal">编辑</button>
          </td>
        </tr>
        </tbody>
      </table>
    </div>

    <!-- 个人信息显示页面 -->
    <div id="profileContent" style="display:none; margin-left: 150px; margin-right: 150px">
      <h4>个人中心</h4>
      <div class="row">
        <div class="col-12 mb-3">
          <label for="profileAvatar">头像</label><br>
          <img id="profileAvatarPreview"   th:src="${user.avatar != null ? user.avatar : '/img/avatar.jpg'}"
               class="rounded-circle" alt="Avatar" style="width: 100px; height: 100px; object-fit: cover;">
          <input type="file" id="profileAvatar" class="form-control mt-2" accept="image/*" style="display: none;">
          <input type="hidden" id="profileAvatarUrl" th:value="${user.avatar}">
        </div>
        <div class="col-12">
          <label for="profileUsername">用户名</label>
          <input type="text" class="form-control" id="profileUsername" th:value="${user.username}" readonly>
        </div>
        <div class="col-12 mt-3">
          <label for="profileNickname">昵称</label>
          <input type="text" class="form-control" id="profileNickname" th:value="${user.nickname}">
        </div>
        <div class="col-12 mt-3">
          <label for="profileAge">年龄</label>
          <input type="text" class="form-control" id="profileAge" th:value="${user.age}">
        </div>
        <div class="col-12 mt-3">
          <label for="profileGender">性别</label>
          <select id="profileGender" class="form-control">
            <option value="0" th:selected="${user.gender == 0}">男</option>
            <option value="1" th:selected="${user.gender == 1}">女</option>
          </select>
        </div>
        <!-- 原始密码 -->
        <div class="col-12 mt-3">
          <label for="profileOldPassword">原始密码</label>
          <input type="password" class="form-control" id="profileOldPassword" placeholder="请输入原始密码">
          <input id = "password" type="hidden" th:value="${user.password}">
        </div>

        <!-- 新密码 -->
        <div class="col-12 mt-3">
          <label for="profilePassword">新密码</label>
          <input type="password" class="form-control" id="profilePassword" placeholder="请输入新密码">
        </div>
        <input type="hidden" id="userid" th:value="${user.id}">

        <div class="col-12 mt-4">
          <button type="button" class="btn btn-primary" id="saveProfileBtn">保存</button>
        </div>
      </div>
    </div>
  </div>

  <!-- 新增/编辑日程信息模态框 -->
  <div class="modal fade" id="addScheduleModal" tabindex="-1" aria-labelledby="addScheduleModalLabel" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="addScheduleModalLabel">新增/编辑日程信息</h5>
        </div>
        <div class="modal-body">
          <div class="mb-3">
            <label for="contentInput" class="form-label">日程内容</label>
            <input type="text" class="form-control" id="contentInput" required>
          </div>
          <div class="mb-3">
            <label for="scheduledateInput" class="form-label">预约时间</label>
            <input type="datetime-local" class="form-control" id="scheduledateInput" required>
          </div>
          <div class="mb-3">
            <label for="remindtimeInput" class="form-label">提醒时间</label>
            <input type="datetime-local" class="form-control" id="remindtimeInput" required>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
          <button type="button" class="btn btn-primary" id="saveScheduleBtn">保存</button>
        </div>
      </div>
    </div>
  </div>
</div>
  <script>
    $(document).ready(function() {
      $('#scheduleMenu').click(function() {
        $('#scheduleContent').show();
        $('#profileContent').hide();
        $('#scheduleMenu').addClass('active');
        $('#profileMenu').removeClass('active');
      });

      $('#profileMenu').click(function() {
        $('#scheduleContent').hide();
        $('#profileContent').show();
        $('#scheduleMenu').removeClass('active');
        $('#profileMenu').addClass('active');
      });

      // 默认显示日程信息管理
      $('#scheduleMenu').click();

      // 保存或更新日程信息
      $('#saveScheduleBtn').click(function () {
        const scheduleId = $(this).data('id');
        const scheduleData = {
          content: $('#contentInput').val(),
          scheduledate: $('#scheduledateInput').val(),
          remindtime: $('#remindtimeInput').val(),
          userid: $('#userid').val()
        };

        if (scheduleId) {
          // 更新日程信息
          $.ajax({
            url: '/schedule/update',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({ ...scheduleData, id: scheduleId }),
            success: function () { location.reload(); },
            error: function (xhr) { console.error("更新日程信息失败: ", xhr.responseText); }
          });
        } else {
          // 新增日程信息
          $.ajax({
            url: '/schedule/save',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(scheduleData),
            success: function () { location.reload(); },
            error: function (xhr) { console.error("新增日程信息失败: ", xhr.responseText); }
          });
        }
      });

      // 编辑日程信息
      $('.updateSchedule').click(function () {
        debugger
        const scheduleId = $(this).data('id');
        $.get('/schedule/' + scheduleId, function (schedule) {
          $('#contentInput').val(schedule.content);
          $('#scheduledateInput').val(formatForDateTimeLocal(schedule.scheduledate));
          $('#remindtimeInput').val(formatForDateTimeLocal(schedule.remindtime));
          $('#saveScheduleBtn').data('id', schedule.id);
          $('#addScheduleModal').modal('show');
        });
      });

      // 将时间格式转换为 datetime-local 所需的格式
      function formatForDateTimeLocal(dateTimeString) {
        if (!dateTimeString) return '';
        const dateObj = new Date(dateTimeString);
        return dateObj.toISOString().slice(0, 16); // YYYY-MM-DDTHH:mm
      }


      // 删除日程信息
      $(document).on('click', '#deleteSchedule', function () {
        const scheduleId = $(this).data('id');
        if (confirm("您确定要删除该日程信息吗？")) {
          $.ajax({
            url: '/schedule/delete/' + scheduleId,
            type: 'DELETE',
            success: function () { location.reload(); },
            error: function (xhr) { console.error("删除日程信息失败: ", xhr.responseText); }
          });
        }
      });

    // 查询日程信息
      $('#searchSchedule').click(function () {
        const content = $('#content').val();
        const userId = $('#userid').val();
        $.ajax({
          url: '/schedule/search?userId=' + userId + "&content=" + content,
          type: 'GET',
          success: function (data) {
            const tbody = $('#scheduleContent tbody');
            tbody.empty();
            data.forEach(function (schedule) {
              const formattedRemindtime = moment(schedule.remindtime).format('YYYY-MM-DD HH:mm:ss');
              const formattedScheduledate = moment(schedule.scheduledate).format('YYYY-MM-DD HH:mm:ss');

              const row = `
                <tr>
                  <td>${schedule.id}</td>
                  <td>${schedule.username}</td>
                  <td>${schedule.content}</td>
                  <td>${formattedScheduledate}</td>
                  <td>${formattedRemindtime}</td>
                  <td>
                      <button type="button" id="deleteSchedule" class="btn btn-danger btn-sm deleteSchedule" data-id="${schedule.id}">删除</button>
                      <button type="button" id="updateSchedule" class="btn btn-warning btn-sm updateSchedule" data-id="${schedule.id}" data-toggle="modal" data-target="#addScheduleModal">编辑</button>
                  </td>
                </tr>
              `;
              tbody.append(row);
            });
          },
          error: function (xhr) {
            console.error("查询日程信息失败: ", xhr.responseText);
          }
        });
      });
      $('#profileAvatarPreview').click(function() {
        $('#profileAvatar').click();  // 触发隐藏的文件选择框
      });

      // 当用户选择新头像时更新预览
      $('#profileAvatar').change(function(event) {
        const file = event.target.files[0];
        // 如果用户选择了文件
        if (file) {
          const reader = new FileReader();
          reader.onload = function(e) {
            // 更新预览图片
            $('#profileAvatarPreview').attr('src', e.target.result);
            // 使用 FormData 进行文件上传
            const formData = new FormData();
            formData.append("file", file);  // 将选择的文件添加到 FormData 中

            // 发送 AJAX 请求到上传接口
            $.ajax({
              url: '/user/uploadAvatar',  // 你上传头像的接口地址
              type: 'POST',
              data: formData,
              processData: false, // 不处理 data
              contentType: false, // 不设置 contentType 让浏览器自动处理
              success: function(response) {
                // 上传成功后，返回新的头像 URL，更新隐藏字段和头像预览
                $('#profileAvatarUrl').val(response);  // 保存返回的头像路径
                $('#profileAvatarPreview').attr('src', response);  // 更新头像预览
                $('#avatar').attr('src', response)
              },
              error: function(xhr, status, error) {
                console.error("头像上传失败", error);
                alert("头像上传失败，请重试！");
              }
            });
          };
          reader.readAsDataURL(file);  // 读取文件内容
        }
      });

      // 用户信息保存
      $('#saveProfileBtn').click(function() {
        // 获取用户输入的信息
        const userId = $('#userid').val();  // 获取用户ID
        const username = $('#profileUsername').val();  // 获取用户名（不可编辑）
        const nickname = $('#profileNickname').val();  // 获取昵称
        const age = $('#profileAge').val();  // 获取年龄
        const gender = $('#profileGender').val();  // 获取性别
        const avatar = $('#profileAvatarUrl').val();  // 获取头像URL
        const oldPassword = $('#profileOldPassword').val();  // 获取用户输入的原始密码
        const password = $('#password').val() // 原始密码
        const newPassword = $('#profilePassword').val();  // 获取新密码

        debugger
        // 确保原始密码和新密码字段不为空
        if (!oldPassword || oldPassword !== password) {
          alert("原始密码输入错误，请重新输入！");
          return;
        }

        // 创建一个对象保存所有要更新的信息
        const userData = {
          id: userId,
          username: username,
          nickname: nickname,
          age: age,
          gender: gender,
          avatar: avatar,
          password: newPassword
        };

        // 发送 AJAX 请求到后端更新用户信息
        $.ajax({
          url: '/user/update',  // 后端接口地址
          type: 'POST',
          contentType: 'application/json',
          data: JSON.stringify(userData),  // 将数据转换成 JSON 格式
          success: function(response) {
            if (response) {
              // 如果更新成功，提示用户并刷新页面或更新界面
              alert('个人信息更新成功！');
              location.reload();  // 刷新页面
            } else {
              alert('更新失败，请重试！');
            }
          },
          error: function(xhr, status, error) {
            console.error("更新失败: ", error);
            alert('更新失败，请重试！');
          }
        });
      });

      // 提醒功能，基于定时器去做
      setInterval(function () {
        console.log('定时器执行')
        const userId = $('#userid').val();
        $.ajax({
          url: '/schedule/getSchedulesByUserId?userId=' + userId,
          type: 'GET',
          success: function (data) {
            const reminders = [];  //提醒事项
            if (data && data.length > 0) {
              data.forEach(function (schedule) {
                // 判断如果提醒时间小于等于当前时间，但小于等于预约时间，则alter提醒，提醒包括内容、预约时间
                const now = moment();
                const formattedRemindtime = moment(schedule.remindtime);
                const formattedScheduledate = moment(schedule.scheduledate);
                if (formattedRemindtime.isSameOrBefore(now) && formattedRemindtime.isSameOrBefore(formattedScheduledate)) {
                    reminders.push({
                      content: schedule.content,
                      scheduledate: formattedScheduledate.format('YYYY-MM-DD HH:mm:ss')
                    })
                }
              });
              if (reminders.length > 0) {
                let message = '你有以下提醒事项：\n';
                reminders.forEach(function (reminder) {
                  message += `内容：${reminder.content}\n预约时间：${reminder.scheduledate}\n\n`;
                });
                alert(message);
              }
            }
          }
        })
      }, 120000) // 每2分钟检查一次
  });

</script>
</body>
</html>
